import React, { memo, useEffect } from 'react'
import type { FC, ReactNode } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import dayjs from 'dayjs'

import '../../styles/iconfont.css'
import { useMyDispatch, resetAllStore } from '../../store'
import { setCodeAll, setID, setExit } from '../../store/modules/codeall'
import {
  setIsOpen,
  setPassword,
  setTitle,
  setCurrentTime,
  setEndTime,
  setLabel
} from '../../store/modules/create'

import {
  setMdContent,
  setCodeUrl,
  setTheme,
  setShareOrEdit
} from '../../store/modules/success'
import fetchData from '../../request'

interface IProps {
  children?: ReactNode
}

interface codeAllType {
  label: string
  key: string
  language: string
  codeSlice: string
}

interface CodeItem {
  title: string
  isOpen: boolean
  currentTime: string
  label: string[]
  codeAll: codeAllType[]
  codeUrl: string
  endTime: string
  id: string
  theme: string
  mdContent: string
  password: string
}

const ShareCodeByPass: FC<IProps> = () => {
  const dispatch = useMyDispatch()
  const location = useLocation()
  const pw = new URLSearchParams(location.search).get('pw')
  const iidd = new URLSearchParams(location.search).get('id')
  const navigate = useNavigate()

  const dispatchAll = async (result: CodeItem) => {
    dispatch(setCodeAll(result.codeAll))
    dispatch(setID(result.id))
    dispatch(setIsOpen(result.isOpen))
    dispatch(setPassword(result.password))
    dispatch(setTitle(result.title))
    dispatch(setTheme(result.theme))
    dispatch(setCurrentTime(result.currentTime))
    dispatch(setEndTime(result.endTime))
    dispatch(setLabel(result.label))
    dispatch(setMdContent(result.mdContent))
    dispatch(setCodeUrl(result.codeUrl))
    dispatch(setShareOrEdit(true))
    dispatch(setExit(true))
  }

  useEffect(() => {
    const fetchMessage = async () => {
      try {
        const response = await fetchData('/get')
        const data = await response.json()
        const result = data.find(
          (item: CodeItem) => item.password === pw && item.id.includes(iidd!)
        )
        if (result === undefined) {
          resetAllStore()
          navigate('/create')
          return
        } else if (dayjs(result.endTime).isBefore(dayjs())) {
          alert('分享已过期,即将跳转到<创建>页面')
          resetAllStore()
          navigate('/create')
          return
        }
        console.log(result)
        await dispatchAll(result)
        navigate('/success')
      } catch (error) {
        console.error(error)
      }
    }

    fetchMessage()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  return <></>
}

export default memo(ShareCodeByPass)
